package user

import (
	"gitee.com/lishixi/gops/vblog/apps/utils"
	"github.com/go-playground/validator/v10"
	"github.com/infraboard/mcube/v2/exception"
	"github.com/infraboard/mcube/v2/tools/pretty"
	"go.starlark.net/lib/time"
	"golang.org/x/crypto/bcrypt"
)

// 定义持久化对象
var (
	v = validator.New()
)

func New(in *RegistryRequest) (*User, error) {
	if err := in.Validate(); err != nil {
		return nil, exception.NewBadRequest("用户参数校验失败: %s", err)
	}
	return &User{
		ResourceMetaData: *utils.NewResourceMetaData(),
		RegistryRequest:  *in,
	}, nil
}

type User struct {
	// 需要存在数据库里的元数据信息
	utils.ResourceMetaData
	// 用户具体参数
	RegistryRequest
}

func (t *User) String() string {
	return pretty.ToJSON(t)
}
func (*User) TableName() string {
	return "users"
}

func NewRegistryRequest() *RegistryRequest {
	return &RegistryRequest{}
}

type RegistryRequest struct {
	// 用户名
	UserName string `json:"user_name" gorm:"column:user_name;unique;index" validate:"required"`
	// 密码
	Password string `json:"password" gorm:"column:password;type:varchar(255)" validate:"required"`
	//用户 profile 信息
	Profile
	// 用户状态
	Status
}

func (t *RegistryRequest) CheckPassword(password string) error {
	return bcrypt.CompareHashAndPassword([]byte(t.Password), []byte(password))
}

func (t *RegistryRequest) Validate() error {
	return v.Struct(t)
}

type Status struct {
	// 冻结时间
	BlockAt *time.Time `json:"block_at" gorm:"column:block_at"`
	// 冻结原因
	BlockReason string `json:"block_reason" gorm:"column:block_reason;type:text"`
}

func (s *Status) IsBlocked() bool {
	return s.BlockAt != nil
}

type Profile struct {
	// 用户头像
	Avatra string `json:"avatra" gorm:"column:avatra;type:varchar(255)"`
	// 用户昵称
	NickName string `json:"nick_name" gorm:"column:nick_name;type:varchar(100)"`
	// 邮箱
	Email string `json:"email" gorm:"column:email;type:varchar(100)"`
}
